<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\v1;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Request\DiaryRequest;
use App\Service\UserDiaryService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;

class Diary extends AbstractController
{
    /**
     * @Inject
     * @var UserDiaryService
     */
    protected $diaryService;

    /**
     * 增加一个日记.
     */
    public function addDiary(DiaryRequest $diaryRequest): \Psr\Http\Message\ResponseInterface
    {
        $data = $diaryRequest->all();
        Db::beginTransaction();
        try {
            $userId = Context::get('user_id');
            $ret = $this->diaryService->addDiary($userId, $data);
            Db::commit();
            return $this->success([]);
        } catch (\Exception $e) {
            Db::rollBack();
            $code = empty($e->getCode()) ? ErrorCode::SERVER_ERROR : $e->getCode();
            $msg = $e->getMessage();
            return $this->success([], $code, $msg);
        }
    }

    /**
     * 删除日记.
     */
    public function deleteDiary(): \Psr\Http\Message\ResponseInterface
    {
        Db::beginTransaction();
        try {
            $userId = Context::get('user_id');
            $id = $this->request->post('id', '');
            $ret = $this->diaryService->deleteDiary($userId, $id);
            Db::commit();
            return $this->success();
        } catch (\Exception $e) {
            Db::rollBack();
            $code = empty($e->getCode()) ? ErrorCode::SERVER_ERROR : $e->getCode();
            $msg = $e->getMessage();
            return $this->success([], $code, $msg);
        }
    }

    /**
     * 获取日记详情.
     */
    public function getDiaryInfo(): \Psr\Http\Message\ResponseInterface
    {
        $id = $this->request->input('id', '');
        $userId = Context::get('user_id');
        $info = $this->diaryService->getDiaryInfo($userId, $id);
        return $this->success($info);
    }
}
